<script setup lang="ts">
import { useRouter } from 'vue-router'
import ValidCode from "@/components/ValidCode.vue";

const router = useRouter();


// 往右
const moveImageRight = () => {
  // 登录往右
  const imgLogin = document.getElementById('background-login');
  imgLogin.style.transition = 'transform 1.5s'; // 添加过渡效果
  imgLogin.style.transform = 'translateX(100%)'; // 在水平方向上移动图片
  // 注册往右
  const imgRegister = document.getElementById('background-register');
  imgRegister.style.transition = 'transform 1.5s'; // 添加过渡效果
  imgRegister.style.transform = 'translateX(100%)'; // 在水平方向上移动图片
}

// 往左
const moveImageLeft = () => {
  user.value.number = ""
  user.value.password = ""
  user.value.confirmPass = ""
  user.value.phone = ""
  // 登录往左
  const imgLogin = document.getElementById('background-login');
  imgLogin.style.transition = 'transform 1.5s'; // 添加过渡效果
  imgLogin.style.transform = 'translateX(0)'; // 重置位置
  // 注册往左
  const imgRegister = document.getElementById('background-register');
  imgRegister.style.transition = 'transform 1.5s'; // 添加过渡效果
  imgRegister.style.transform = 'translateX(0)'; // 重置位置
}

import { ref, reactive, onUnmounted} from 'vue'

const code = ref('');  // 验证码组件传递过来的code
const user = ref({
  code: '',   // 表单里用户输入的code 验证码
  number: '',
  password: '',
  phone: '',
  confirmPass: ''
})
// 获取验证码
const getCode = (newCode) => {
  code.value = newCode.toLowerCase();
}
// 验证码校验
const validateCode = (rule, value, callback) => {
  if (user.value.code === '') {
    callback(new Error('请输入验证码'))
  } else if (code.value !== user.value.code) {
    callback(new Error('验证码错误'))
  } else {
    callback()
  }
}
// 再次密码校验
const rePasswordValid = (rule, value, callback) => {
  //当没有输入密码时，再次确认密码不会生效
  if (user.value.password === '') {
    callback()
  } else if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== user.value.password) {
    callback(new Error('两次密码不一致'))
  } else {
    callback();
  }
}
// 手机号校验
const validatePhone = (rule, value, callback) => {
  const regex = /^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-7|9])|(?:5[0-3|5-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1|8|9]))\d{8}$/; // 定义手机号正则表达式
  if (!regex.test(value)) {
    callback(new Error('请输入正确的手机号')); // 验证失败，返回错误信息
  } else {
    callback(); // 验证成功，不返回任何信息
  }
}
// 学号验证
const validateNumber = (rule, value, callback) => {
  const currentYear = new Date().getFullYear(); // 获取当前年份
  if (!/^\d{10}$/.test(value)) {
    callback(new Error('学号格式有误'));
  } else if (value.substr(0, 4) < 1956 || value.substr(0, 4) > currentYear) {
    callback(new Error('学号格式有误'));
  } else {
    callback();
  }
}
import type { FormInstance, FormRules } from 'element-plus'
// 表单规则
const rules = reactive<FormRules<typeof user>>({
  number: [
    { required: true, message: '请输入学号,测试号：2022212001，密码：123456', trigger: 'blur' },
    { validator: validateNumber, trigger: 'blur' } // 添加自定义的学号验证规则
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
  ],
  code: [
    { validator: validateCode, trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { validator: validatePhone, trigger: 'blur' } // 添加自定义的手机号验证规则
  ],
  confirmPass: [
    { validator: rePasswordValid, trigger: 'blur' }
  ],
})

import { userLoginService, userRegisterService } from "@/api/user.js";
import { ElMessage } from "element-plus";
import { useTokenStore } from "@/stores/token.js";
import { useUserInfoStore } from "@/stores/userInfo.js";

const tokenStore = useTokenStore();
const userInfoStore = useUserInfoStore();
// 登录功能
const login = async () => {
  // 向后端发请求
  let result = await userLoginService(user.value);
  // 把token存到pinia中
  tokenStore.setToken(result.data.token);
  // 把用户信息存到pinia中
  const userInfo = {
    name: result.data.name,
    number: result.data.number
  }
  userInfoStore.setInfo(userInfo)
  ElMessage.success("登录成功")
  router.push("/home")
}

// 登录提交时校验表单数据是否正确
const loginFormRef = ref<FormInstance>()
const loginSubmitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      //console.log('submit!')
      // 验证通过，调用登录方法
      login()
    } else {
      console.log('error submit!')
      return false
    }
  })
}

// 注册功能
const register = async () => {
  // 向后端发送请求
  const result = await userRegisterService(user.value);
  // 后端成功回调没用msg，所以无需ElMessage.success(result.msg ? result.msg :"注册成功")
  ElMessage.success("注册成功，请前往登录")
}

// 注册提交时校验表单数据是否正确
const registerFormRef = ref<FormInstance>()
const registerSubmitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {
      console.log('submit!')
      // 验证通过，调用注册方法
      register()
    } else {
      console.log('error submit!')
      return false
    }
  })
}

// 登录按钮
const loginBtn = ref()
// Enter键和登录按钮绑定
const handleKeyDown = (event) => {
  if (event.keyCode === 13) {
    loginBtn.value.$el.click()
  }
}

// 添加键盘事件监听
document.addEventListener('keydown', handleKeyDown)
// 销毁监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleKeyDown)
})



</script>


<template>
  <div class="scrollable">

    <!--登录-->
    <div style="background-color: #8ac0f2" class="background-login" id="background-login">
      <!-- 左上角logo -->
<!--       <div style="position: absolute; top: 10px; left: 10px;">
        <img src="@/assets/school.png" alt="" style="width: 20%">
      </div> -->
      <div
        style="display: flex; background-color: white; opacity: 0.85;width: 50%; border-radius: 30px; overflow: hidden">
        <div style="flex: 1">
          <img src="@/assets/login.png" alt="" style="width: 100%">
        </div>
        <div style="flex: 1; display: flex; align-items: center; justify-content: center">
          <el-form :model="user" style="width: 80%" :rules="rules" ref="loginFormRef">
            <div style="font-size: 20px; font-weight: bold; text-align: center; margin-bottom: 20px">欢迎登录懂你小助手</div>
            <el-form-item prop="number">
              <el-input prefix-icon="user" size="default" placeholder="请输入学号" v-model="user.number"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input prefix-icon="lock" size="default" show-password placeholder="请输入密码"
                v-model="user.password"></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <div style="display: flex;width: 100%">
                <el-input placeholder="请输入验证码" prefix-icon="circle-check" size="default" style="flex: 1"
                  v-model="user.code"></el-input>
                <div style="flex: 1; height: 36px">
                  <ValidCode @update:value="getCode" />
                </div>
              </div>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="width: 100%" @click="loginSubmitForm(loginFormRef)" ref="loginBtn"> 登 录
              </el-button>
            </el-form-item>
            <div style=" display: flex">
              <div class="text">
                还没有账号？请 <span style="color: #0f9876; cursor: pointer" @click="moveImageRight()">注册</span></div>
              <div style="flex: 1; text-align: right" class="text"><span style="color: #0f9876; cursor: pointer"
                  @click="goForget()">忘记密码</span></div>
            </div>
          </el-form>
        </div>
      </div>
    </div>

    <!--注册-->
    <div style="height: 100vh; display: flex; align-items: center; justify-content: center; background-color: #152c56"
      class="background-register" id="background-register">
      <!-- 左上角logo -->
<!--       <div style="position: absolute; top: 10px; left: 10px;">
        <img src="@/assets/school.png" alt="" style="width: 20%">
      </div> -->
      <div
        style="display: flex; background-color: white; opacity: 0.85;width: 50%; border-radius: 30px; overflow: hidden">
        <div style="flex: 1">
          <img src="@/assets/register.png" alt="" style="width: 100%">
        </div>
        <div style="flex: 1; display: flex; align-items: center; justify-content: center">
          <el-form :model="user" style="width: 80%" :rules="rules" ref="registerFormRef">
            <div style="font-size: 20px; font-weight: bold; text-align: center; margin-bottom: 20px">欢迎注册懂你小助手</div>
            <el-form-item prop="number">
              <el-input prefix-icon="user" size="default" placeholder="请输入学号" v-model="user.number"></el-input>
            </el-form-item>
            <el-form-item prop="password">
              <el-input prefix-icon="lock" size="default" show-password placeholder="请输入密码"
                v-model="user.password"></el-input>
            </el-form-item>
            <el-form-item prop="confirmPass">
              <el-input prefix-icon="lock" size="default" show-password placeholder="请确认密码"
                v-model="user.confirmPass"></el-input>
            </el-form-item>
            <el-form-item prop="phone">
              <el-input prefix-icon="phone" size="default" placeholder="请输入手机号" v-model="user.phone"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" style="width: 100%" @click="registerSubmitForm(registerFormRef)">注 册</el-button>
            </el-form-item>
            <div class="text">
              <div style="flex: 1">已经有账号了？请 <span style="color: #6e77f2; cursor: pointer"
                  @click="moveImageLeft()">登录</span></div>
            </div>
          </el-form>
        </div>
      </div>
    </div>

  </div>
</template>

<style scope>
.scrollable {
  /* 隐藏滚动条*/
  overflow: hidden;
}

/* 登录界面背景图片 */
.background-login {
  height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-position: center bottom;
  background-image: url("@/assets/banner-login.jpg");
  background-repeat: no-repeat;
  background-size: contain;
  /* 1528px */

}

/* 注册界面背景图片 */
.background-register {
  position: fixed;
  left: -100%;
  /* 将界面移出屏幕左侧 */
  top: 0;
  /* 设置界面距离顶部的距离，可以根据需要调整 */
  width: 100%;
  /* 使界面占满整个屏幕宽度 */
  height: 100vh;
  /* 使界面占满整个屏幕高度 */
  background-image: url("@/assets/banner-register.jpg");
  background-repeat: no-repeat;
  background-size: contain;
  background-color: #1772F6;
}

.text {
  flex: 1;
  color: #555;
  font-size: 10px;
  margin: 0;
  padding: 0;
}
</style>